<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 用户提现
 * Class ConsumerCash
 * @author heyu
 */
class WithdrawCash extends MY_Controller {
	
	/**
	 * @var DlnUserModel
	 */
    public $mMuser = null;

	public function __construct(){
		parent::__construct();
        $this->loadModel('DlnUserModel', 'mMuser', 'deliveryman');
	}

	/**
	 * 首页
	 */
	public function index(){
		$data = array(
			'title' =>'提现',
			'status' => $this->getStatus()
		);
		$this->view('deliveryman/withdrawCash/home',$data,'datatable,validation,datepicker');
	}

	/**
	 * 列表
	 */
	public function getList(){
        $data = $this->getLists();
		if(!empty($data['data'])){
			foreach ($data['data'] as $k =>$v){
				$tA = json_decode($v['bank'], true);
				$data['aaData'][$k][] = $v['name'].'<span style="color:grey;">（'.$v['mobile'].'）</span>';
				$data['aaData'][$k][] = is_array($tA) ? $tA['bank'].'<span style="color:grey;">（'.$tA['code'].'）<span>' : '';
				$data['aaData'][$k][] = - $v['amount'];
                $data['aaData'][$k][] = isset($v['action_time']) ? dateFormat($v['action_time'], true) : '';
                $data['aaData'][$k][] = dateFormat($v['addtime'], true);
                $tS = '';
                if($v['status'] == 3){
                	$tS = '<a href="javascript:void(0);" title="查看拒绝原因" class="view-btn">
                			<span class="content hide">'.nl2br($v['refuse_remarks']).'</span><i class="fa fa-eye"></i></a>';
                }
                $data['aaData'][$k][] = $this->getStatus($v['status'],true).$tS;
				if ($v['status'] == 1) {
                    $btnConfig = adminCreateBtn(array(
                        'label' => ' 已打款',
                        'icon' => '',
                        'attr' => array(
                            'href' => getUrl('deliveryman/withdrawCash/changeStatus') . '?id=' . $v['id'] . '&status=2',
                            'class' => 'ajax-request-btn btn default btn-xs blue-stripe',
                            'alert-message' => "确认要标记为已打款吗？"
                        ),
                        'tag' => 'a',
                        'permissions' => array(
                            'module' => 'deliveryman',
                            'key' => 'withdraw_cash-status'
                        )
                    ));
                    $btnConfig .= ' ' . adminCreateBtn(array(
                        'label' => ' 拒绝',
                        'icon' => '',
                        'attr' => array(
                            'href' => 'javascript:;',
                            'class' => 'btn default btn-xs red-stripe edit-btn',
                            'data-id' => $v['id'],
                        ),
                        'tag' => 'a',
                        'permissions' => array(
                            'module' => 'deliveryman',
                            'key' => 'withdraw_cash-status'
                        )
                    ));
                }else{
                    $btnConfig = '';
                }
				$data['aaData'][$k][] = $btnConfig;
			}
		}

		unset($data['data']);
		echo json_encode($data);
	}

	/**
	 * 获取状态
	 *
	 * @param	integer	$key
	 * @param	boolean	$show	是否显示
	 * @return	mixed
	 */
	public function getStatus($key = null, $show = false){

		$config = array(
            '1' => '申请中',
            '2' => '已打款',
            '3' => '已拒绝'
		);

		if($key !== null){

			if(isset($config[$key]) && ! $show){
				return $config[$key];
			}

			if(isset($config[$key]) && $show){

				if($key == 3){
					return '<span class="label label-danger">'.$config[$key].'</span>';
				}else if($key == 2){
					return '<span class="label label-success">'.$config[$key].'</span>';
				}else if($key == 1){
					return '<span class="label label-warning">'.$config[$key].'</span>';
				}
			}
			return '';
		}

		return $config;
	}

	/**
	 * 修改状态
	 */
	public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
            array('status', '状态', 'required|is_list[3,2]'),
        );
        $status = (int)get('status');
        if ($status == 3){
            $vConf[] = array('reason', '拒绝理由', 'required');
        }
        $this->formDataValidation($vConf, array(
            'id' => get('id'),
            'status' => get('status'),
            'reason' => get('reason')
        ));
		$id = get('id');
		
		$this->db->select('deliveryman_id,status,amount')->where('id', $id)->where('type', 2);
        $info = $this->mMuser->getOne($this->mMuser->tbAmountDetails);
        if ( ! $info){
            $this->ajaxReturn(0, '数据不存在');
        }
        if ($info['status'] != 1){
            $this->ajaxReturn(0, '已处理，不能重复操作');
        }
        $data = ['status' => $status,'action_time' => time()];

        //配送员信息
        $delivery = $this->mMuser->getInfo($info['deliveryman_id']);
        if(!$delivery){
            $this->ajaxReturn(0, '配送员不存在');
        }
        $this->db->trans_begin();


        if ($status == 3){
            //申请拒绝 退回提现金额
            $amount = ltrim($info['amount'], '-');
            $balance = $delivery['amount']+(int)$amount;

            $this->db->where('id', $info['deliveryman_id']);
            if( ! $this->mMuser->update($this->mMuser->tbUser, array('amount' => $balance))){
                $this->db->trans_rollback();
                $this->appReturn(0, '退款金额失败');
            }

            $data['refuse_remarks'] = trim(get('reason'));
        }

        $this->db->where('id', $id);
		if( ! $this->mMuser->update($this->mMuser->tbAmountDetails, $data)){
			$this->db->trans_rollback();
			$this->ajaxReturn(0, '保存失败');
		}
		
		if($status == 3){
			$data = [
						'deliveryman_id' => $info['deliveryman_id'],
						'amount' => -$info['amount'],
						'type' => 3,
						'status' => 2,
						'order_id' => 0,
						'addtime' => time(),
						'action_time' => time()
			];
			if( ! $this->mMuser->insert($this->mMuser->tbAmountDetails, $data)){
				$this->db->trans_rollback();
				$this->ajaxReturn(0, '保存失败');
			}
		}
		
		$this->db->trans_commit();
		$this->ajaxReturn(1, '已保存');
	}

	public function getLists($export = array()){
        $action_time_from = strtotime(get('action_time_from'));
        $action_time_to = strtotime(get('action_time_to'));
        $addtime_from = strtotime(get('addtime_from'));
        $addtime_to = strtotime(get('addtime_to'));
        $status = intval(get('status'));
        $keyword = trim(get('keyword'));

        if ($keyword){
            $this->db->where('u.name like "%'.$keyword.'%" or u.mobile like "%'.$keyword.'%"');
        }
        if($status){
            $this->db->where('a.status', $status);
        }
        if($action_time_from){
            $this->db->where('a.action_time >=', $action_time_from);
        }
        if($action_time_to){
            $this->db->where('a.action_time <', strtotime('+1day', $action_time_to));
        }
        if($addtime_from){
            $this->db->where('a.addtime >=', $addtime_from);
        }
        if($addtime_to){
            $this->db->where('a.addtime <', strtotime('+1day', $addtime_to));
        }

        $this->db->select('a.id,u.name,u.mobile,a.amount,a.status,a.action_time,bank,a.addtime,a.refuse_remarks')
            ->join($this->mMuser->tbUser.' u', 'u.id = a.deliveryman_id')
            ->where('a.type', 2)
            ->order_by('a.id desc');
        if (empty($export)){
            return $this->mMuser->pagination($this->mMuser->tbAmountDetails.' a');
        }else{
            $tA = $this->mMuser->appPage($this->mMuser->tbAmountDetails.' a', $export['page'], false, $export['pageNumber']);
            return $tA['list'];
        }
    }
    /**
     * 导出
     */
    public function export(){
        $filename = '商户提现'.date('Y-m-d',time()).'.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('商户,提现方式,金额,完成时间,添加时间,状态','gb2312','utf-8')."\n";
        $pageNumber = 500;
        $page = 1;
        $_GET['found_type'] = 4;
        while(true){
            $data =$this->getLists(array('page' => $page, 'pageNumber' => $pageNumber));
            if(empty($data)){
                break;
            }
            $page ++;
            foreach($data as $v){
                $tA = json_decode($v['bank'], true);
                $bank = is_array($tA) ? $tA['bank'].'（'.$tA['code'].'）' : '';
                $actionTime = isset($v['action_time']) ? dateFormat($v['action_time'], true) : '';
                $addtime = dateFormat($v['addtime'], true);
                $tS = '';
                if($v['status'] == 3){
                    $tS = '【拒绝原因：'.nl2br($v['refuse_remarks']).'】';
                }
                $status = $this->getStatus($v['status']).$tS;
                echo mb_convert_encoding($v['name'].'（'.$v['mobile'].'）'.','.$bank.','.- $v['amount'].','.$actionTime.','.$addtime.','.$status, 'gb2312','utf-8')."\n";
            }
        }
    }
}
